<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input :placeholder="$t('table.name')" v-model="listQuery.name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input :placeholder="$t('table.scode')" v-model="listQuery.scode" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-select v-model="listQuery.sale" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in saleOptions" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="listQuery.available" :placeholder="$t('table.available')" clearable style="width: 90px" class="filter-item">
        <el-option v-for="(item, index) in availableOptions" :key="index" :label="item.name" :value="item.value" />
      </el-select>
      <el-cascader
          :placeholder="$t('placeholder.select')"
          v-model="listQuery.category_id"
          :options="categoryOptions"
          clearable
          change-on-select
          class="filter-item"
        ></el-cascader>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.addproduct') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="danger" icon="el-icon-delete" @click="handleMulDelete">{{ $t('table.batch_delete') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      :default-sort = "{prop: 'id', order: 'descending'}"
      @sort-change="productListSort"
      @selection-change="handleSelectionChange"
      style="width: 100%;">
      <el-table-column
        type="selection"
        width="35">
      </el-table-column>
      <el-table-column :label="$t('table.id')" align="center" width="65" sortable="custom" prop="id">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.image')" min-width="120px" align="center">
        <template slot-scope="scope">
          <img :src="scope.row.mphoto_url ? scope.row.mphoto_url : defaultPic" class="plistImg" style="max-width: 100px;">
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.name')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.curname }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.scode')" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.scode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.available')" class-name="status-col" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_available | availableFilter">{{ scope.row.available_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.sale')" class-name="status-col" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.is_sale | saleFilter">{{ scope.row.sale_name }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.created_at')" width="160px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.created_at }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.sort')" width="160px" align="center" sortable="custom" prop="sort">
        <template slot-scope="scope">
          <span><el-input v-model="scope.row.sort" type="number" min="0" @change="handelProductSort(scope.row)" /></span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button size="mini" type="danger" @click="deleteData(scope.row)">{{ $t('table.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="900px">
      <el-tabs v-model="editableTabsValue" type="card">
      <el-tab-pane
        :label="$t('table.basicInfo')"
        name="basicInfo"
      >
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="160px" style="margin-left:30px;">
          <el-form-item :label="$t('table.area')">
            <el-select v-model="temp.area_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
              @change="handleLocationChange"
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in areaOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.location')">
            <el-select
              v-model="temp.location_id"
              style="width: 450px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')" >
              <el-option-group
                v-for="area in locationOptions"
                :key="area.id"
                :label="area.name"
                :value="area.id">
                <el-option
                  v-for="location in area.locations"
                  :key="location.id"
                  :label="location.name"
                  :value="location.id">
                </el-option>
              </el-option-group>
            </el-select>
            <el-checkbox v-model="is_location_all" @change="handleLocationAll">{{ $t('table_element.available.all') }}</el-checkbox>
          </el-form-item>
          <el-form-item :label="$t('table.available')">
            <el-radio v-model="temp.is_available" label="1" name="is_avaliable">{{ $t('table_element.available.on') }}</el-radio>
            <el-radio v-model="temp.is_available" label="0" name="is_avaliable">{{ $t('table_element.available.un') }}</el-radio>
          </el-form-item>
          <el-form-item :label="$t('table.sale')">
            <el-radio v-model="temp.is_sale" label="1" name="is_sale">{{ $t('table_element.sale.on') }}</el-radio>
            <el-radio v-model="temp.is_sale" label="0" name="is_sale">{{ $t('table_element.sale.un') }}</el-radio>
          </el-form-item>

          <el-form-item :label="$t('table.pshortcode')">
            <el-input style="width: 440px;" class="filter-item" v-model="temp.scode" name="productShortCode" />
            <el-button style="margin-left: 10px;" type="primary"  @click="getShortCode">{{ $t('table.ax_match') }}</el-button>
          </el-form-item>
          <el-form-item :label="$t('table.category')">
            <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="temp.category_id"
              :options="categoryOptions"
              change-on-select
              style="width: 450px"
            ></el-cascader>
            <!-- <el-select v-model="temp.category_id" class="filter-item" :placeholder="$t('placeholder.select')">
              <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select> -->
          </el-form-item>
          <!-- <el-form-item :label="$t('table.ord_menu_cate')">
            <el-select v-model="temp.omcategory" class="filter-item" :placeholder="$t('placeholder.select')">
              <el-option v-for="(item, index) in ordMenuCateOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item> -->

          <el-form-item  :label="$t('table.price')">
            <el-row :gutter="10">
              <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.qty') }}</div></el-col>
              <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.price') }}</div></el-col>
              <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.kcal') }}</div></el-col>
              <el-col :span="4"><div class="grid-content bg-purple">{{ $t('table.capacity') }}</div></el-col>
              <el-col :span="3"><div class="grid-content bg-purple">{{ $t('table.protein') }}</div></el-col>
              <el-col :span="4"><div class="grid-content bg-purple">{{ $t('table.pcode') }}</div></el-col>
            </el-row>
            <el-row :gutter="10" v-for="(item, index) in temp.price" :key="index">
              <el-col :span="3">
                <div class="grid-content bg-purple">
                  <el-input v-model.number="item.qty" name="qty[]" />
                </div>
              </el-col>
              <el-col :span="3">
                <div class="grid-content bg-purple">
                  <el-input v-model="item.price" name="price[]" />
                </div>
              </el-col>
              <el-col :span="3">
                <div class="grid-content bg-purple">
                  <el-input v-model="item.kcal" name="kcal[]" />
                </div>
              </el-col>
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  <el-input v-model="item.capacity" name="capacity[]" />
                </div>
              </el-col>
              <el-col :span="3">
                <div class="grid-content bg-purple">
                  <el-input v-model="item.protein" name="protein[]" />
                </div>
              </el-col>
              <el-col :span="4">
                <div class="grid-content bg-purple">
                  <el-input v-model="item.pcode" name="pcode[]" />
                </div>
              </el-col>
            </el-row>

            <el-row >
              <el-button style="font-size:20px;" type="text" @click="addPrice()" class="el-icon-circle-plus-outline" ></el-button>
              <el-button style="font-size:20px;" type="text" @click="delPrice()" class="el-icon-remove-outline" ></el-button>
            </el-row>
          </el-form-item>

          <el-form-item :label="$t('table.tags')">
            <el-select
              v-model="temp.tag_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in tags"
                :key="item.id"
                :label="item.tag"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('table.ingredients')">
            <el-select
              v-model="temp.ingredient_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in ingredientOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('table.benefits')">
            <el-select
              v-model="temp.benefit_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in benefitOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <!-- <el-form-item :label="$t('table.supplements')">
            <el-select
              v-model="temp.supplement_id"
              style="width: 560px;"
              multiple
              filterable
              allow-create
              default-first-option
              :placeholder="$t('placeholder.select')">
              <el-option
                v-for="item in supplementOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item> -->

          <el-form-item :label="$t('table.master_photo')" class="upload-from" >
            <!-- <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <el-button size="small" type="primary">{{$t('table.browse')}}</el-button>
                  <img v-if="temp.mphoto" :src="temp.mphoto" class="avatar">
            </el-upload> -->
            <el-upload
              class="upload-demo"
              action=""
              :show-file-list="false"
              :auto-upload="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-change="changeFile">
              <el-button size="small" type="primary">{{$t('table.browse')}}</el-button>
            </el-upload>
            <a :href="temp.mphoto_url" target="_blank" v-if="temp.mphoto">
              <img :src="temp.mphoto_url" class="avatar" >
            </a>
          </el-form-item>

          <el-form-item :label="$t('table.sort')">
            <el-input v-model="temp.sort" name="sort" min="0" type="number" style="width: 100px" />
          </el-form-item>

          <template>
            <el-tabs v-model="activeName" >
              <el-tab-pane label="en" name="first">
                <el-form-item :label="$t('table.name')" required>
                  <el-input v-model="temp.name" name="name" />
                </el-form-item>
                <el-form-item :label="$t('table.description')">
                  <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.description"></el-input>
                </el-form-item>
                <el-form-item :label="$t('table.content')">
                  <tinymce :height="300" id="fContent" v-model="temp.content"/>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="zh-ch" name="second">
                <el-form-item :label="$t('table.name')">
                  <el-input v-model="temp.cnname" name="cnname" />
                </el-form-item>
                <el-form-item :label="$t('table.description')">
                  <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.cndescription"></el-input>
                </el-form-item>
                <el-form-item :label="$t('table.content')">
                  <tinymce :height="300" id="fCNContent" v-model="temp.cncontent"/>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="zh-hk" name="third">
                <el-form-item :label="$t('table.name')">
                  <el-input v-model="temp.hkname" name="hkname" />
                </el-form-item>
                <el-form-item :label="$t('table.description')">
                  <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.hkdescription"></el-input>
                </el-form-item>
                <el-form-item :label="$t('table.content')">
                  <tinymce :height="300" id="fHKContent" v-model="temp.hkcontent"/>
                </el-form-item>
              </el-tab-pane>
              <el-tab-pane label="zh-tw" name="fourth">
                <el-form-item :label="$t('table.name')">
                  <el-input v-model="temp.twname" name="twname" />
                </el-form-item>
                <el-form-item :label="$t('table.description')">
                  <el-input type="textarea" :rows="2" :placeholder="$t('placeholder.input')" v-model="temp.twdescription"></el-input>
                </el-form-item>
                <el-form-item :label="$t('table.content')">
                  <tinymce :height="300" id="fTWContent" v-model="temp.twcontent"/>
                </el-form-item>
              </el-tab-pane>
            </el-tabs>
          </template>
        </el-form>
      </el-tab-pane>
      <el-tab-pane
        :label="$t('table.nutrilonFacts')"
        name="nutrilonFacts"
      >
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="185px" style="margin-left:30px;">

          <!--<el-form-item :label="$t('table.unit_for_per')">
            <el-input v-model="temp.nutrition.per" name="per" style="width: 200px;"/>
            <el-input v-model="temp.nutrition.unit" name="unit" style="width: 100px;"/>
          </el-form-item>
          <el-row :gutter="18" style="height:30px; font-weight:700; border-bottom: #eeee 1px solid; margin-bottom: 20px;">
            <el-col :span="5"><div class="grid-content bg-purple">Facts Name</div></el-col>
            <el-col :span="8"><div class="grid-content bg-purple">Value </div></el-col>
            <el-col :span="4"><div class="grid-content bg-purple">Unit</div></el-col>
          </el-row> -->
          <el-row  v-for="(item, index) in nutritionVals" :key="index" :gutter="50" style="margin-bottom: 20px">
            <el-col :span="12">
              <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="item.nutrition_id"
              :options="nutritionOptions"
              change-on-select
              @change="changeNutrition(item.nutrition_id, index)"
              style="width:400px"
              ></el-cascader>
            </el-col>
            <el-col :span="10"> <el-input v-model="item.per" type="number" name="energy" style="width: 200px;"/> &nbsp;&nbsp;{{item.unit}}</el-col>
          </el-row>
          <el-row >
              <el-button style="font-size:20px;" type="text" @click="addNutrition()" class="el-icon-circle-plus-outline" ></el-button>
              <el-button style="font-size:20px;" type="text" @click="delNutrition()" class="el-icon-remove-outline" ></el-button>
          </el-row>
          <!-- <el-form-item :label="$t('table.energy')">
            <el-input v-model="temp.nutrition.energy" name="energy" style="width: 300px;"/> Kcal
          </el-form-item>
          <el-form-item :label="$t('table.protein')">
            <el-input v-model="temp.nutrition.nprotein" name="protein" style="width: 300px;" /> g
          </el-form-item>

          <el-form-item :label="$t('table.total_fat')">
            <el-input v-model="temp.nutrition.totalfat" name="total_fat" style="width: 300px;" /> g
          </el-form-item>

          <el-form-item :label="$t('table.saturated_fat')">
            <el-input v-model="temp.nutrition.saturatedfat" name="saturated_fat" style="width: 300px;" /> g
          </el-form-item>
          <el-form-item :label="$t('table.trans_fat')">
            <el-input v-model="temp.nutrition.transfat" name="trans_fat" style="width: 300px;" /> g
          </el-form-item>
          <el-form-item :label="$t('table.cholesterol')">
            <el-input v-model="temp.nutrition.cholesterol" name="cholesterol" style="width: 300px;" /> mg
          </el-form-item>
          <el-form-item :label="$t('table.total_carbohydrates')">
            <el-input v-model="temp.nutrition.totalcarbohydrates" name="total_carbohydrates" style="width: 300px;" /> g
          </el-form-item>
          <el-form-item :label="$t('table.dietary_fibre')">
            <el-input v-model="temp.nutrition.dietaryfibre" name="dietary_fibre" style="width: 300px;" /> g
          </el-form-item>
          <el-form-item :label="$t('table.sugars')">
            <el-input v-model="temp.nutrition.sugars" name="sugars" style="width: 300px;" /> g
          </el-form-item>
          <el-form-item :label="$t('table.sodium')">
            <el-input v-model="temp.nutrition.sodium" name="sodium" style="width: 300px;" /> mg
          </el-form-item> -->
        </el-form>
      </el-tab-pane>
    </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { fetchList, fetchShow, fetchStore, fetchUpdate, fetchDelete, fetchBatchDelete, fetchSort } from '@/api/product'
import { fetchAll as fetchLocation, fetchGroup as fetchLocationGroup } from '@/api/location'
import { fetchUpimg } from '@/api/upload'
import { fetchCategoryTree } from '@/api/nutrition'
import waves from '@/directive/waves' // Waves directive
import { parseTime, getUploadImageUrl } from '@/utils'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Tinymce from '@/components/Tinymce'
import PriceTable from '@/components/PriceTable'
/* import ProductNurtition from '@/components/ProductNurtition' */
import i18n from '@/lang/index'

export default {
  name: 'Product',
  components: { Pagination, Tinymce },
  directives: { waves },
  filters: {
    availableFilter(status) {
      const availableMap = [
        'danger',
        'success'
      ]
      return availableMap[status]
    },
    saleFilter(status) {
      const saleMap = [
        'danger',
        'success'
      ]
      return saleMap[status]
    }
  },
  data() {
    return {
      defaultPic: require('../../../assets/empty.jpg'),
      activeName: 'first',
      imageUrl: getUploadImageUrl(),
      isAvailable: 2,
      is_location_all: false,
      isSale: 2,
      tableKey: 0,
      list: null,
      content: ``,
      total: 0,
      listLoading: true,
      listQuery: {
        category_id: [],
        page: 1,
        limit: 20,
        available: 2,
        sale: 2,
        name: '',
        scode: '',
        lang: i18n.locale,
        area: this.$store.getters.area,
        order: 'id',
        sort: 'desc',
      },
      // tags: [],
      product_ids: [],
      locationOptions: [],
      availableOptions: [{ 'value': 2, 'name': i18n.t('table_element.available.all') }, { 'value': 1, 'name': i18n.t('table_element.available.on') }, {'value': 0, 'name': i18n.t('table_element.available.un') }],
      saleOptions: [{ 'value': 2, 'name': i18n.t('table_element.sale.all') }, { 'value': 1, 'name': i18n.t('table_element.sale.on') }, {'value': 0, 'name': i18n.t('table_element.sale.un') }],
      showReviewer: false,
      temp: {
        id: '',
        is_available: '1',
        is_sale: "0",
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        content: '',
        cncontent: '',
        hkcontent: '',
        twcontent: '',
        description: '',
        cndescription: '',
        hkdescription: '',
        twdescription: '',
        area: 96,
        sort: 0,
        price: [
          {
            qty: 0,
            price: 0,
            kcal: '',
            capacity: '',
            protein: '',
            pcode: ''
          }
        ],
        nutritions: [],
        area_id: [96],
        location_id: [],
        tag_id: [],
        ingredient_id: [],
        // supplement_id: [],
        benefit_id: [],
        scode: '',
        mphoto: '',
        mphoto_url: '',
        omcategory: 1,
        category_id: []
      },
      nutritionVals: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        mphoto: [{ required: true, message: 'main photo is required', trigger: 'blur' }]
      },
      downloadLoading: false,
      editableTabsValue: 'basicInfo'
    }
  },
  created() {
    this.getList(),
    this.getLocation()
  },
  mounted() {
    var _this = this
    this.getCategoryList()
  },
  computed: {
    areaOptions: function () {
        return this.$store.state.locale.areas
    },
    // ordMenuCateOptions: function () {
    //     return this.$store.state.locale.productMmcAlls
    // },
    tags: function () {
        return this.$store.state.locale.alltag
    },
    categoryOptions: function () {
        return this.$store.state.locale.categoryTree
    },
    ingredientOptions: function () {
        return this.$store.state.locale.ingredients
    },
    benefitOptions: function () {
        return this.$store.state.locale.benefits
    },
    // supplementOptions: function () {
    //     return this.$store.state.locale.supplements
    // }
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        var data = response.data
        this.list = data.data.data
        this.total = data.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: 'Successful operation',
        type: 'success'
      })
      row.status = status
    },
    getLocation() {// 地址列表
      let params = {
        area: this.temp.area_id
      }
      fetchLocationGroup(params).then((res) => {
        this.locationOptions = res.data.data
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        is_available: '1',
        is_sale: '0',
        name: '',
        cnname: '',
        hkname: '',
        twname: '',
        content: '',
        cncontent: '',
        hkcontent: '',
        twcontent: '',
        description: '',
        cndescription: '',
        hkdescription: '',
        twdescription: '',
        area: 96,
        sort: 0,
        price: [
          {
            qty: 0,
            price: 0,
            kcal: '',
            capacity: '',
            protein: '',
            pcode: ''
          }
        ],
        nutritions: [],
        area_id: [96],
        location_id: [],
        tag_id: [],
        ingredient_id: [],
        // supplement_id: [],
        benefit_id: [],
        scode: '',
        mphoto: '',
        mphoto_url: '',
        omcategory: 1,
        category_id: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.nutritions = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent('')
        window.tinymce.get('fCNContent').setContent('')
        window.tinymce.get('fHKContent').setContent('')
        window.tinymce.get('fTWContent').setContent('')
      })
    },
    createData() {
      this.temp.nutritions = JSON.parse(JSON.stringify(this.nutritionVals))
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
          // this.temp.author = 'vue-element-admin'
          // this.temp.mphoto = this.temp.mphotos[0]
          this.temp.lang = i18n.locale
          fetchStore(this.temp).then(() => {
            this.list.unshift(this.temp)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Create Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.nutritionVals = JSON.parse(JSON.stringify(this.temp.nutritions))
      this.temp.is_available = this.temp.is_available.toString()
      this.temp.is_sale = this.temp.is_sale.toString()
      this.temp.timestamp = new Date(this.temp.timestamp)
      /* this.temp.mphotos = []
      if (this.temp.mphoto) {
        let file = { name: 'mphoto', url: this.temp.mphoto }
        this.temp.mphotos.push(file)
      } */
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].clearValidate()
        window.tinymce.get('fContent').setContent(this.temp.content)
        window.tinymce.get('fCNContent').setContent(this.temp.cncontent)
        window.tinymce.get('fHKContent').setContent(this.temp.hkcontent)
        window.tinymce.get('fTWContent').setContent(this.temp.twcontent)
      })
    },
    updateData() {
      this.temp.nutritions = JSON.parse(JSON.stringify(this.nutritionVals))
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.lang = i18n.locale
          const tempData = Object.assign({}, this.temp)
          tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
          fetchUpdate(this.temp.id, tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      console.log(row);
      this.$notify({
        title: 'Success',
        message: 'Delete Success!',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    deleteData(row) {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchDelete(row.id).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    handleMulDelete() {
      this.$confirm('Confirm deletion?', 'Message', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        fetchBatchDelete({ product_id: this.product_ids }).then(response => {
          var data = response.data
          if (data.code == 0) {
            this.$notify({
              title: 'Success',
              message: 'Delete Success!',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: 'Cancel'
        })
      })
    },
    /* getUploadImageUrl() {
      return getUploadImageUrl()
    },
    handleImagesSuccess(res, file) {
      if (res.code === 0) {
        if (this.activeName === 'first') {
          this.temp.en_source_path = res.data.paths[0].path
          this.en_imageUrl = res.data.imageDomain + res.data.paths[0].path
        }
        if (this.activeName === 'second') {
          this.temp.cn_source_path = res.data.paths[0].path
          this.cn_imageUrl = res.data.imageDomain + res.data.paths[0].path
        }
        if (this.activeName === 'third') {
          this.temp.hk_source_path = res.data.paths[0].path
          this.hk_imageUrl = res.data.imageDomain + res.data.paths[0].path
        }
        if (this.activeName === 'fourth') {
          this.temp.tw_source_path = res.data.paths[0].path
          this.tw_imageUrl = res.data.imageDomain + res.data.paths[0].path
        }
      } else {
        alert(res.data.msg)
      }
    }, */
    handleAvatarSuccess(res, file) {
      this.temp.mphoto = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    changeFile(file, fileList) {
      var This = this;
      // console.log(file)
      //this.imageUrl = URL.createObjectURL(file.raw);
      var reader = new FileReader();
      reader.readAsDataURL(file.raw);
      reader.onload = function(e){
          // this.result // 这个就是base64编码了
          This.imageUrl = this.result
          fetchUpimg({img: this.result}).then((res) => {
            if (res.data && res.data.data && res.data.data.paths && res.data.data.paths.length > 0) {
              This.temp.mphoto = res.data.data.paths[0].path
              This.temp.mphoto_url = (res.data.data.paths[0].path.indexOf('http')==0 || res.data.data.paths[0].path.indexOf('https')==0) ? res.data.data.paths[0].path : res.data.data.imageDomain + '/' + res.data.data.paths[0].path
            }
          })
      }
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
        const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    handelProductSort(row) {
      fetchSort(row.id, event.target.value).then((res) => {
        if (res.data.code == 0) {
          this.$notify({
            title: 'Success',
            message: 'Update Success!',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    productListSort(params) {
      // console.log(params.order)
      this.listQuery.order = params.prop
      this.listQuery.sort = params.order == 'ascending' ? 'asc' : 'desc'
      this.getList()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    addPrice() {
      const item = {
        qty: 0,
        price: 0,
        kcal: '',
        capacity: '',
        protein: '',
        pcode: ''
      }
      this.temp.price.push(item)
    },
    delPrice() {
      let len = this.temp.price.length
      if (len > 0) {
          this.temp.price.splice(len-1)
      }
    },
    getShortCode() {
      // 获取shortCode
      // console.log(this.temp.productShortCode)
    },
    handleLocationChange() {
      this.getLocation();
    },
    getCategoryList() {
      // 获取营养列表
      fetchCategoryTree().then(response => {
          var data = response.data.data
          data.forEach(element => {
              element.nutrition_id = element.value
              element.per = element.label
              if (element.children && element.children.length > 0) {
                element.children.forEach(ele => {
                  ele.nutrition_id = ele.value
                  ele.per = ele.label
                  return ele
                })
              }
              return element
          })
          this.nutritionOptions = data
      })
    },
    addNutrition() {
      this.temp.nutritions = JSON.parse(JSON.stringify(this.nutritionVals))
      const item = {
          nutrition_id: 0,
          per: '',
          unit: ''
      }
      this.nutritionVals.push(item)
    },
    delNutrition() {
      let len = this.nutritionVals.length
      if (len > 0) {
          this.nutritionVals.splice(len-1)
      }
      this.temp.nutritions = JSON.parse(JSON.stringify(this.nutritionVals))
    },
    isAdd(val) {
      let a = []
      let isTrue = false
      this.temp.nutritions.forEach(ele => {
        a = a.concat(ele.nutrition_id)
      })
      return a
    },
    changeNutrition(val, index) {
      // 改变营养
      let t = val.length
      /* if(t > 1 && !this.isAdd(val[0])) {
        this.$alert('<strong class="orange">Please enter your superior</strong>', 'Message', {
            dangerouslyUseHTMLString: true
        })
      } else { */
      let retIds = this.isAdd(this.nutritionVals[index].nutrition_id)
      for (let i = 0; i < this.nutritionOptions.length; i++ ) {
        if (t === 1 && val[0] === this.nutritionOptions[i].value) {
          this.nutritionVals[index].unit = this.nutritionOptions[i].unit
        }
        if (t > 1 && this.nutritionOptions[i].children && this.nutritionOptions[i].children.length > 0) {
          let children = this.nutritionOptions[i].children
          for (let j = 0; j < children.length; j++ ) {
            if(retIds.indexOf(val[0]) === -1) {
              if (val[1] === children[j].value) {
                let data = {
                  nutrition_id: [val[0]],
                  per: children[j].per,
                  unit: children[j].unit
                }
                this.nutritionVals.push(data)
              }
            }
            if (val[1] === children[j].value) {
              this.nutritionVals[index].unit = children[j].unit
              return
            }
          }
        }
      }
      // }
    },
    handleLocationAll() {
      let area, location;
      this.temp.location_id = [];
      if (this.is_location_all) {
        for(area in this.locationOptions) {
          for(location in this.locationOptions[area].locations) {
            this.temp.location_id.push(this.locationOptions[area].locations[location].id);
          }
        }
      }
    },
    handleSelectionChange(val) {
      val.forEach(element => {
        if (this.product_ids.indexOf(element.id) == -1) {
          this.product_ids.push(element.id)
        }
      })
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.upload-from{
    .avatar{
        // height: 40px;
        max-width: 200px;
        max-height: 200px;
        border: 1px solid #eee;
    }
}
.plistImg{
    max-width: 120px;
    max-height: 120px;
}
</style>
